package com.bt.springboot.common.exception;

import com.bt.springboot.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 *
 * @author zkx
 * @Date 2022/8/9 14:20
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public Result<?> exceptionHandler(Exception e) {
		log.info("系统异常", e);
		return Result.failure("系统异常");
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public Result<?> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		BindingResult exceptions = e.getBindingResult();
		// 判断异常中是否有错误信息，如果存在就是使用异常中的消息，否则使用默认消息
		if (exceptions.hasErrors()) {
			List<ObjectError> errors = exceptions.getAllErrors();
			// 取第一条错误参数
			FieldError fieldError = (FieldError) errors.get(0);
			return Result.failure(fieldError.getDefaultMessage());
		}
		return Result.failure("请求参数错误");
	}

	/**
	 * 处理BusinessException异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = BusinessException.class)
	public Result businessExceptionHandler(BusinessException e) {
		return Result.failure(e.getCode(),e.getErrMsg());
	}
}
